# -*- coding: utf-8 -*-

import pytest

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
# !使用API接口UiAutomator2Options创建能力---推荐
def create_appium_session_by_api(custom_opts = None):
    # !UiAutomator2Options默认就已经初始化automationName和platformName两个参数
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options)

# !使用原始的字典键值对创建能力---该方法会被废弃
def create_appium_session_by_dict(custom_opts:dict):
    return webdriver.Remote(f'http://{APPIUM_HOST}:{APPIUM_PORT}', custom_opts)

# 客户端创建会话连接所需要的最少参数
def test_general_capability_of_min_args(start_appium_service):
    min_opts = {
        "appium:automationName":"uiautomator2",
        "platformName": "android"
    }
    driver = create_appium_session_by_dict(min_opts)
    print(f"drviver package is {driver.current_package}")
    driver.quit()

    driver = create_appium_session_by_api()
    print(f"drviver activity is {driver.current_activity}")
    driver.quit()

# 保留会话打开的应用和数据
def test_open_contact(start_appium_service):
    # 创建一个会话连接，打开联系人应用
    # noReset设置为True，会话退出后不会清零应用
    custom_opts_noreset = {
        "appium:noReset" : True,
        "appPackage": "com.google.android.dialer",
        "appActivity": ".extensions.GoogleDialtactsActivity"
    }
    driver = create_appium_session_by_api(custom_opts_noreset)
    driver.quit() # 模拟会话终止

    # 创建一个新的会话连接，不做具体动作
    driver = create_appium_session_by_api()
    # 由于前一个会话未清理应用，因此该会话连接之后，被测设备仍停留在联系人应用界面
    assert driver.current_activity == ".extensions.GoogleDialtactsActivity"

